#!/usr/bin/env python
#_*_coding:utf-8_*_
# Copyright (c) 2012 crunch <hymm91@gmail.com>
# All rights reserved

#$Id$

import sys,os
import subprocess

"""执行shell脚本"""

use_shell = sys.platform.startswith("win")

def ErrorExit(msg, app=''):
  """Print an error message to stderr and exit."""
  if msg:
    if app:
      print >>sys.stderr, "Error: %s\n===================================================================" % app
    print >>sys.stderr, msg
  sys.exit(1)


def RunShellWithReturnCode(command, print_output=False,
                           universal_newlines=True,
                           env=os.environ, app=''):
  """Executes a command and returns the output from stdout and the return code.

  Args:
    command: Command to execute.
    print_output: If True, the output is printed to stdout.
                  If False, both stdout and stderr are ignored.
    universal_newlines: Use universal_newlines flag (default: True).

  Returns:
    Tuple (output, return code)
  """
  p = subprocess.Popen(command, cwd=env['PWD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                       shell=use_shell, universal_newlines=universal_newlines,
                       env=env)
  #if print_output:
  #  output_array = []
  #  while True:
  #    line = p.stdout.readline()
  #    if not line:
  #      break
  #    print line.strip("\n")
  #    output_array.append(line)
  #  output = "".join(output_array)
  #else:
  output = p.stdout.read()
  p.wait()
  errout = p.stderr.read()
  if print_output and errout:
    print >>sys.stderr, errout
  p.stdout.close()
  p.stderr.close()
  return output,  p.returncode


def RunShell(command, silent_ok=False, universal_newlines=True,
             print_output=False, env=os.environ, app=''):
  data, retcode = RunShellWithReturnCode(command, print_output,
                                         universal_newlines, env)
  if retcode:
    ErrorExit("Got error status from %s:\n%s" % (command, data), app=app)
  if not silent_ok and not data:
    ErrorExit("No output from %s" % command, app=app)
  return data

#$Id$
